package org.ssm.demo.service;

import org.apache.http.client.utils.DateUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.record.pivottable.StreamIDRecord;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.ssm.demo.entity.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Service
public class ExportService {

	private Logger log = Logger.getLogger(getClass());

	@Autowired
	private IUserService userService;

	/**
	 * 批量导出性能指标
	 * @param nodeId 节点id
	 * @param exportType 导出类型：对应os_biz_export_config中的exportType,vm等
	 * @param dateType ： 昨天，今天，一周,一月
	 * @param param ：资源ID等
	 * @param out：输出流
	 * @throws IOException
	 */
	public void getSelectedExcel(String nodeId, String exportType, String dateType, String param, String params_name, ServletOutputStream out, String fileName) throws IOException  {
		log.info("批量导出功能 前台传入参数："+"node_id="+nodeId+"&exportType="+exportType+"&dateType="+dateType+"&param="+param);
		/**************处理时间start***************/
		int date = 0;
		if(dateType.equals("yesterday")){date = 1;
		}else if(dateType.equals("week")){date = 7;
		}else if(dateType.equals("month")){date = 30;
		}
		/**************处理时间end***************/
		//创建一个HSSFWorkbook，对应一个Excel文件
		XSSFWorkbook wb = new XSSFWorkbook();
		wb = getWorkbookObj(exportType,param,params_name,dateType,date,wb,fileName);
		wb.write(out);
		out.close();
	}

	private XSSFWorkbook getWorkbookObj(String exportType, String param, String params_name, String dateType, int date, XSSFWorkbook wb, String fileName) {
		String[] title = null;
		String[] params = param.split(",");
		String[] params_names = params_name.split(",");
		if(exportType.equals("vm")){//云主机
			title = new String[]{"CPU利用率(%)", "内存使用率(%)", "磁盘使用量(GB)", "流入流量速率(Mbps)"};
			for(int k=0;k<params.length;k++){
				List<User> Datalist = null;
				Datalist = userService.getLimit(1,3);
				if(Datalist.size()>0){
					String[][] content = new String[Datalist.size()][];
					for(int i = 0;i<Datalist.size();i++){
						content[i] = new String[title.length];
						User obj = Datalist.get(i);
						content[i][0] = String.valueOf(obj.getId());
						content[i][1] = String.valueOf(obj.getAge());
						content[i][2] = obj.getPassword();
						content[i][3] = obj.getUserName();
					}
					wb =exportUtils(exportType,wb,params_names[k],content,title,fileName);
				}else{
					XSSFSheet sheet = wb.createSheet(exportType+"_"+params_names[k]);
					XSSFRow head = sheet.createRow(0);
					XSSFCell header = head.createCell(0);
					header.setCellValue("暂无数据");
				}
			}
		}
		return wb;
	}

	private XSSFWorkbook exportUtils(String exportType, XSSFWorkbook wb, String param, String[][] content, String[] title, String fileName) {

		XSSFSheet sheet = wb.createSheet(exportType+"-"+param);

		XSSFRow head = sheet.createRow(0);
		XSSFCell header = head.createCell(0);
		header.setCellValue(fileName);

		XSSFRow row = sheet.createRow(1);

		XSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

		XSSFCell cell = null;
		for(int i=0;i<title.length;i++){
			cell = row.createCell(i);
			cell.setCellValue(title[i]);
			cell.setCellStyle(style);
		}
		for(int i=0;i<content.length;i++){
			row = sheet.createRow(i + 2);
			for(int j=0;j<content[i].length;j++){
				//将内容按顺序赋给对应的列对象
				row.createCell(j).setCellValue(content[i][j]);
				row.setRowStyle(style);
			}
		}
		return wb;
	}

	public String[] parse(String source)
	{
		String[] sources = source.split("]");
		String[] result = new String[sources.length];
		int flag = 0;
		for(String field : sources)
		{
			String value = field.substring(field.indexOf("[")+1).trim();
			if(!value.equals(""))
			{
				result[flag++] = value;
			}
		}
		if(flag == 0)
			return null;
		if(flag != sources.length)
		{
			String[] tmp = new String[flag];
			System.arraycopy(result, 0, tmp, 0, flag);
			result = tmp;
		}
		return result;
	}

}
